package it.antonio.ilpizze.db.index.btree.file;

import it.antonio.ilpizze.db.index.btree.Entry;
import it.antonio.ilpizze.db.index.utils.FPerst;
import it.antonio.ilpizze.db.index.utils.FilePointer;
import it.antonio.ilpizze.db.io.IOFile;

public class FileEntry<K extends Comparable<K>, V> implements Entry<K, V>, FilePointer, FileBTreeConstants {
	
	/*
	 *  type|key|value
	 */
	
	private IOFile file;
	private long position;
	private FPerst<K> keyPersister;
	private FPerst<V> valuePersister;
	
	public FileEntry(IOFile file, long position, FPerst<K> keyPersister, FPerst<V> valuePersister) {
		this.file = file;
		this.position = position;
		this.keyPersister = keyPersister;
		this.valuePersister = valuePersister;
		
		file.position(position);
		int typeCheck = file.readInt();
		if(typeCheck != ENTRY){
			throw new IllegalStateException("Invalid Element");
		}
		
	}
	
	
	@Override
	public K key() {
		file.position(position + SIZE_INT);
		return keyPersister.read(file);
	}

	@Override
	public V value() {
		file.position(position + SIZE_INT + keyPersister.space());
		return valuePersister.read(file);
	}

	@Override
	public void value(V value) {
		file.position(position + SIZE_INT + keyPersister.space());
		valuePersister.persist(file, value);
	}

	@Override
	public long position() {
		return position;
	}
	
	@Override
	public long space() {
		return  SIZE_INT + keyPersister.space() + valuePersister.space();
	}
	
}
